// 认证服务 - 管理用户认证状态和令牌
import { API_CONFIG } from '@/config/api'

export interface User {
  id: number
  name: string
  phone: string
  email?: string | null
  avatar?: string
  status?: number
  created_at?: string
  updated_at?: string
  email_verified_at?: string | null
}

export interface LoginResponse {
  success: boolean
  message: string
  data: {
    token: string
    user: User
  }
}

export interface RegisterResponse {
  success: boolean
  message: string
  data: {
    token: string
    user: User
  }
}

class AuthService {
  private readonly TOKEN_KEY = 'auth_token'
  private readonly USER_KEY = 'user_data'

  /**
   * 获取当前存储的令牌
   */
  getToken(): string | null {
    return localStorage.getItem(this.TOKEN_KEY)
  }

  /**
   * 获取当前用户信息
   */
  getUser(): User | null {
    const userData = localStorage.getItem(this.USER_KEY)
    return userData ? JSON.parse(userData) : null
  }

  /**
   * 检查用户是否已登录
   */
  isAuthenticated(): boolean {
    return !!this.getToken()
  }

  /**
   * 保存认证信息
   */
  private saveAuthData(token: string, user: User): void {
    localStorage.setItem(this.TOKEN_KEY, token)
    localStorage.setItem(this.USER_KEY, JSON.stringify(user))
  }

  /**
   * 清除认证信息
   */
  clearAuthData(): void {
    localStorage.removeItem(this.TOKEN_KEY)
    localStorage.removeItem(this.USER_KEY)
  }

  /**
   * 用户登录
   */
  async login(phone: string, password: string): Promise<LoginResponse> {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ phone, password }),
      })

      const data: LoginResponse = await response.json()

      if (!response.ok || !data.success) {
        throw new Error(data.message || '登录失败')
      }

      if (data.success && data.data?.token && data.data?.user) {
        this.saveAuthData(data.data.token, data.data.user)
      }

      return data
    } catch (error) {
      throw error
    }
  }

  /**
   * 用户注册
   */
  async register(
    name: string,
    phone: string,
    password: string,
    password_confirmation: string
  ): Promise<RegisterResponse> {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/auth/register`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name,
          phone,
          password,
          password_confirmation,
        }),
      })

      const data: RegisterResponse = await response.json()

      if (!response.ok || !data.success) {
        throw new Error(data.message || '注册失败')
      }

      if (data.success && data.data?.token && data.data?.user) {
        this.saveAuthData(data.data.token, data.data.user)
      }

      return data
    } catch (error) {
      throw error
    }
  }

  /**
   * 更新用户资料
   */
  async updateProfile(updates: { name?: string; avatar?: File }): Promise<User> {
    const token = this.getToken()
    if (!token) {
      throw new Error('请先登录')
    }

    try {
      const formData = new FormData()
      if (updates.name) formData.append('name', updates.name)
      if (updates.avatar) formData.append('avatar', updates.avatar)

      const response = await fetch(`${API_CONFIG.BASE_URL}/auth/updateProfile`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
        body: formData,
      })

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ message: '更新失败' }))
        throw new Error(errorData.message || '更新失败')
      }

      const data = await response.json()

      if (data.success && data.user) {
        this.saveAuthData(token, data.user)
        return data.user
      }

      throw new Error('更新失败')
    } catch (error) {
      throw error
    }
  }

  /**
   * 获取用户信息（验证令牌有效性）
   */
  async fetchUserInfo(): Promise<User> {
    const token = this.getToken()
    if (!token) {
      throw new Error('请先登录')
    }

    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/auth/me`, {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      })

      if (!response.ok) {
        throw new Error('Token已过期或无效')
      }

      const data = await response.json()

      if (data.success && data.data) {
        this.saveAuthData(token, data.data)
        return data.data
      }

      throw new Error('获取用户信息失败')
    } catch (error) {
      // Token无效，清除本地数据
      this.clearAuthData()
      throw error
    }
  }

  /**
   * 用户登出
   */
  logout(): void {
    this.clearAuthData()
  }

  /**
   * 获取认证头
   */
  getAuthHeaders(): Record<string, string> {
    const token = this.getToken()
    return {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      ...(token && { 'Authorization': `Bearer ${token}` }),
    }
  }
}

// 导出单例实例
export const authService = new AuthService()
